package com.wfs.suanfa.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 模拟100人 每个人请求十次接口记录请求数
 * synchronized来实现锁
 *
 */
public class Demo01 {
    static   int count=0;
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        int threadSize=100;
         final CountDownLatch countDownLatch=new CountDownLatch(threadSize);
        for (int i=0;i<100;i++){
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        for (int j=0;j<10;j++){
                            request();
                        }
                    }catch (Exception e){

                    }finally {
                        countDownLatch.countDown();
                    }
                }
            });
            thread.start();
        }
        //保证100个线程执行完毕
        countDownLatch.await();
        long startEnd = System.currentTimeMillis();
        System.out.println("count:"+count+";耗时:"+(startEnd-startTime));
    }

    public  synchronized static void request() throws InterruptedException {
        TimeUnit.MICROSECONDS.sleep(5);
        //解析为(需了解 jvm引擎) count=count+1 非线程安全;
        count++ ;
    }
}
